package com.yunxitest.yunxitest.item.hdmi

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.ImageFormat
import android.graphics.SurfaceTexture
import android.hardware.camera2.*
import android.media.ImageReader
import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.util.Log
import android.view.Surface
import android.view.TextureView
import android.widget.Toast
import com.yunxitest.yunxitest.Interface.IDetectItem
import com.yunxitest.yunxitest.Interface.IResultCallback
import com.yunxitest.yunxitest.R
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*


/**
 * Created by apple on 2018/10/19.
 */
class Hdmi1Camera (var mContext: Context,var inResultCallback: IResultCallback?) : IDetectItem {


    /**
     * An additional thread for running tasks that shouldn't block the UI.
     */
    private var mBackgroundThread: HandlerThread? = null

    /**
     * A [Handler] for running tasks in the background.
     */
    private var mBackgroundHandler: Handler? = null

    var TAG="Hdmi2Camera"

    private val previewWidth = 1280

    private val previewHeight = 720


    var texture_view1: TextureView?= null
    private var imageReader: ImageReader? = null

    private fun start() {
        texture_view1 = (mContext as Activity).findViewById(R.id.texture_view1)//在获取
        mBackgroundThread = HandlerThread("CameraBackground")
        mBackgroundThread?.start()
        mBackgroundHandler = Handler(mBackgroundThread?.looper)

        if (texture_view1?.isAvailable!!) {
            doOpenCamera()
        } else {
            texture_view1?.surfaceTextureListener = mSurfaceTextureListener
        }

    }

    var isSuccess:Boolean?=false

    override fun startDetect() {
        start()
        isSuccess=false
        Handler(Looper.getMainLooper()).postDelayed({
            if(!isSuccess!!){
                inResultCallback?.fail("Hdmi1Camera time out")
            }
        },3000)
    }

    override fun finish() {

    }
    /**
     * [texture_view1.SurfaceTextureListener] handles several lifecycle events on a
     * [texture_view1].
     */
    private val mSurfaceTextureListener = object :  TextureView.SurfaceTextureListener {

        override fun onSurfaceTextureAvailable(surfaceTexture: SurfaceTexture,
                                               width: Int, height: Int) {
//            encoderRunnable = VideoEncoderRunnable()
//
//            Thread(encoderRunnable).start()
            doOpenCamera()
        }

        override fun onSurfaceTextureSizeChanged(surfaceTexture: SurfaceTexture,
                                                 width: Int, height: Int) {
        }

        override fun onSurfaceTextureDestroyed(surfaceTexture: SurfaceTexture): Boolean {
            return true
        }

        override fun onSurfaceTextureUpdated(surfaceTexture: SurfaceTexture) {

        }
    }

    @SuppressLint("MissingPermission")
    private fun doOpenCamera() {
        val manager = mContext?.getSystemService(Context.CAMERA_SERVICE) as CameraManager
        try {
            val cameraId = manager.cameraIdList[0]//这个可能会有很多个，但是通常都是两个，第一个是后置，第二个是前置；
            val characteristics = manager.getCameraCharacteristics(cameraId)
            val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)!!
            //mPreviewSize = map.getOutputSizes(SurfaceTexture.class)[0];
            manager.openCamera(cameraId, object : CameraDevice.StateCallback() {
                override fun onOpened(camera: CameraDevice) {
                    Log.i(TAG, "onOpened")
                    createCameraPreview(camera)
                }

                override fun onDisconnected(camera: CameraDevice) {
                    Log.i(TAG, "onDisconnected")
                    camera.close()
                    inResultCallback?.fail("openCamera onDisconnected")
                    isSuccess=true
                }

                override fun onError(camera: CameraDevice, error: Int) {
                    Log.e(TAG, "onError -> " + error)
                    camera.close()
                    inResultCallback?.fail("openCamera onError")
                    isSuccess=true
                }
            }, mBackgroundHandler)//这个指定其后台运行，如果直接UI线程也可以，直接填null；
            Log.i(TAG, "open Camera " + cameraId)
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }

    }

    fun createCameraPreview(cameraDevice: CameraDevice?) {
        try {
            if (null == cameraDevice) {
                Log.i(TAG, "updatePreview error, return")
                return
            }
            setUpImageReader()
            val captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD)
            val texture = texture_view1?.surfaceTexture
            texture?.setDefaultBufferSize(previewWidth, previewHeight)
            val textureSurface = Surface(texture)
            val imageSurface = imageReader?.surface
            captureRequestBuilder.addTarget(imageSurface)
            captureRequestBuilder.addTarget(textureSurface)
            cameraDevice.createCaptureSession(Arrays.asList(textureSurface,imageSurface), object : CameraCaptureSession.StateCallback() {
                //配置要接受图像的surface
                override fun onConfigured(cameraCaptureSession: CameraCaptureSession) {
                    captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO)
                    try {
                        cameraCaptureSession.setRepeatingRequest(captureRequestBuilder.build(), null, mBackgroundHandler)//成功配置后，便开始进行相机图像的监听
                    } catch (e: CameraAccessException) {
                        e.printStackTrace()
                    }
                }
                override fun onConfigureFailed(cameraCaptureSession: CameraCaptureSession) {
                    Toast.makeText(mContext, "Configuration change", Toast.LENGTH_LONG).show()
                    inResultCallback?.fail("onConfigureFailed")
                    isSuccess=true
                }
            }, mBackgroundHandler)
        } catch (e: CameraAccessException) {
            e.printStackTrace()
        }

    }

    private fun setUpImageReader() {

        imageReader = ImageReader.newInstance(previewWidth, previewHeight,
                ImageFormat.YUV_420_888, 10)
        imageReader?.setOnImageAvailableListener({ reader ->
            val image = reader.acquireLatestImage()
            (mContext as Activity).runOnUiThread({
                inResultCallback?.success()
                isSuccess=true
                inResultCallback=null
            })
            if (image != null) {
                image!!.close()
            }
        }, mBackgroundHandler)
    }

}